package com.mxpio.erp.workshop.policy.impl;

import java.math.BigDecimal;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.technology.entity.BomInfo;
import com.mxpio.erp.common.technology.entity.BomInfoLine;
import com.mxpio.erp.common.technology.service.BomInfoService;
import com.mxpio.erp.common.technology.vo.VersionVO;
import com.mxpio.erp.common.workshop.entity.ManufactureOrder;
import com.mxpio.erp.common.workshop.entity.ManufactureOrderItem;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;

@Component
public class ManufactureOrderSavePolicy extends SmartCrudPolicyAdapter {
	
	@Autowired
    private BomInfoService bomInfoService;

	@Override
	public boolean beforeInsert(CrudContext context) {
		Object o = context.getEntity();
		if(o instanceof ManufactureOrder){
			return saveBomLine((ManufactureOrder) o);
		}
		return true;
	}
	
	@Override
	public boolean beforeUpdate(CrudContext context) {
		Object o = context.getEntity();
		if(o instanceof ManufactureOrder){
			ManufactureOrder order = JpaUtil.linq(ManufactureOrder.class).idEqual(((ManufactureOrder) o).getBizNo()).findOne();
			if(!order.getReferenceDate().equals(((ManufactureOrder) o).getReferenceDate())
					&&OrderStatusEnums.OrderStatus.PLAN.getStatusCode().equals(((ManufactureOrder) o).getOrderStatus())){
				return saveBomLine((ManufactureOrder) o);
			}
		}
		if(o instanceof ManufactureOrderItem){
			return false;
		}
		return true;
	}
	
	private boolean saveBomLine(ManufactureOrder o){
		String bizNo = ((ManufactureOrder) o).getBizNo();
		BigDecimal quantity = ((ManufactureOrder) o).getOrderQuantity();
		VersionVO vo = new VersionVO();
		vo.setDate(((ManufactureOrder) o).getReferenceDate());
		BomInfo bomInfo = bomInfoService.listBom(((ManufactureOrder) o).getProductItemCode(), vo);
		if(CollectionUtils.isEmpty(bomInfo.getBomInfoLineList())){
			return false;
		}
		JpaUtil.lind(ManufactureOrderItem.class).equal("bizNo", bizNo).delete();
		int i = 0;
		for(BomInfoLine line : bomInfo.getBomInfoLineList()){
			i++;
			ManufactureOrderItem item = new ManufactureOrderItem();
			item.setBizNo(bizNo);
			item.setQuantity(quantity.multiply(line.getItemConsumption()));
			item.setItemCode(line.getItemCode());
			item.setItemName(line.getItemName());
			item.setItemSpec(line.getItemSpec());
			item.setLineNo(i+"");
			JpaUtil.save(item);
		}
		return true;
	}
}
